<?php
/**
 * Created by PhpStorm.
 * User: MG
 * Date: 2021/1/13
 * Time: 11:50
 */

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\BillOrder;
use app\admin\model\CheckBill;
use app\admin\model\DepositOrder;
use app\admin\model\ElectricDegrees;
use app\admin\model\ErrLog;
use app\admin\model\Manufacturer;
use app\admin\model\ManufacturerUrl;
use app\admin\model\RechargeOrder;
use app\admin\model\wraning\WarningFacility;
use app\admin\model\wraning\WarningLog;
use app\common\library\Sms;
use EasyWeChat\Factory;
use app\common\controller\Api;
use function EasyWeChat\Kernel\data_get;
use function fast\e;
use GuzzleHttp\Client;
use think\Db;
use think\Response;
use app\common\model\User as UserModel;
use Exception;
use fast\Random;
use app\common\library\Upload;
use app\common\exception\UploadException;
use think\Config;
use app\common\model\User;
use app\admin\model\Discount;

class Wechat extends  Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public  static function options()
    {

        $config=[
            'app_id'=>config('site.wechat_appid'),
            'secret'=>config('site.wechat_appsecret'),
            'token'=>config('site.wechat_token'),
            'cert_path'=>ROOT_PATH . str_replace('/', DS, substr(get_addon_config('epay')['wechat']['cert_client'], 1)),
            'key_path'=>ROOT_PATH . str_replace('/', DS, substr(get_addon_config('epay')['wechat']['cert_key'], 1)),
            'notify_url'=>''
        ];
//        var_dump($config['app_id']);die;
        return $config;
    }

    /**
     * 公众号用户退款
     */
    public function deposit()
    {
        $uid=$this->request->request('uid');
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        $config=self::options();
        $config['key']=get_addon_config('epay')['wechat']['key'];
        $config['mch_id']=get_addon_config('epay')['wechat']['mch_id'];
        $app=Factory::payment($config);
        $is_has=DepositOrder::where('orderid',$out_trade_no)->find();
        if ($is_has) $out_trade_no=date("YmdHis") . mt_rand(100000, 999999);
        $user=\app\admin\model\User::where('id',$uid)->find();
        if ($user['money']==0) $this->error('您的余额为0，不能退款！');
        $data['user_id']=$uid;
        $data['orderid']=$out_trade_no;
        $data['title']='退款';
        $data['amount']=$user['money'];
        $data['createtime']=time();
        $data['status']=1;
        $res=DepositOrder::create($data);
        if ($res){
            $res1=$app->transfer->toBalance([
                'partner_trade_no'=>$out_trade_no,
                'openid'=>$user['openid'],
                'check_name'=>'NO_CHECK',
                'amount'=>bcmul($user['money'],100),
                'desc'=>'用户退款'
            ]);
            if ($res1['result_code']=='SUCCESS'){
                \app\admin\model\User::update(['money'=>0],['id'=>$uid]);
                $this->success('成功');
            }else{
                $this->error($res1['err_code_des']);
            }
        }

    }

    /**
     * 获取微信jsdk配置信息
     */
    public function config()
    {
        $url=$this->request->request('url');
        $app=Factory::officialAccount(self::options());
        $apiList = ['editAddress', 'openAddress', 'updateTimelineShareData', 'updateAppMessageShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'];
        $app->jssdk->setUrl(urldecode($url));
        $list=$app->jssdk->buildConfig($apiList);

        $this->success('成功',json_decode($list,true));
    }

    public function sendWarn()
    {
        $jo=file_get_contents('php://input');
        $jos=json_decode($jo);
        $name=$jos->{'name'};
        $device_id=$jos->{'device_id'};
        $device_address=$jos->{'device_address'};
        $belong_phone=$jos->{'belong_phone'};
        $phones=$jos->{'phones'};
//        file_put_contents('sendWarn1',print_r($this->request,true));
//        file_put_contents('sendWarn2',print_r($jo,true));
//        file_put_contents('sendWarn3',print_r($jos,true));
//        file_put_contents('sendWarn4',print_r($device_id,true));
//        file_put_contents('sendWarn5',print_r($device_address,true));
//        file_put_contents('sendWarn6',print_r($belong_phone,true));
//        file_put_contents('sendWarn7',print_r($phones,true));
//        file_put_contents('sendWarn8',print_r($name,true));
        $data['device_number']=$device_id;
        $data['address']=$device_address;
        $data['phones']=implode(',',$phones);
        $data['mobile']=$belong_phone;
        $data['name']=$name;
        $data['createtime']=time();

        $users=UserModel::where('mobile','in',$phones)->column('openid','mobile');
        $app=Factory::officialAccount(self::options());
        for($i=0;$i<count($phones);$i++){
            if (array_key_exists($phones[$i],$users)){

                $app->template_message->send([
                    'touser'=>$users[$phones[$i]],
                    'template_id'=>'WQBlDGc8-h9NKC4VCixeN1dXTG4ErRfHFkwmiScgpVM',
//                    'template_id'=>'ytyX-WhUu2xIpKviORO3dwMoAJV-tqtWRTF3nTQPp2w',
                    'data'=>[
                        'keyword1'=>$name.'（手机号：'.$belong_phone.'）携电池进入了'.$device_address,
                        'keyword2'=>date('Y-m-d H:i:s',time())
                    ]
                ]);
            }
        }
        $res=(new WarningLog())->save($data);
        if ($res) $this->success('成功');
        else $this->error('失败');

    }



    /**
     * 预警设备 添加 第三方
     */
    public function addWarnDistrict()
    {
        $jo=file_get_contents('php://input');
        $jos=json_decode($jo);
//        $device_id=$jos->{'device_id'};
//        $province=$jos->{'province'};
//        $citys=$jos->{'citys'};
//        $area=$jos->{'area'};
//        $street=$jos->{'street'};
//        $community=$jos->{'community'};
//        $village=$jos->{'village'};
//        $address=$jos->{'address'};
//        $longitude=$jos->{'longitude'};
//        $latitude=$jos->{'latitude'};
//        $status=$jos->{'status'};
//        $data['device_number']=$device_id;
//        $data['province']=$province;
//        $data['citys']=$citys;
//        $data['area']=$area;
//        $data['street']=$street;
//        $data['community']=$community;
//        $data['village']=$village;
//        $data['address']=$address;
//        $data['city']=$province.'/'.$citys.'/'.$area;
//        $data['longitude']=$longitude;
//        $data['latitude']=$latitude;
//        $data['status']=$status;
//        $data['createtime']=time();
        file_put_contents('addWarnDistrict1',print_r($this->request,true));
        file_put_contents('addWarnDistrict2',print_r($jo,true));
        file_put_contents('addWarnDistrict3',print_r($jos,true));
//        $res=WarningFacility::create($data);
//        if ($res) $this->success('成功');
//        else $this->error('失败');
    }



    /**
     * 微信公众号官方 验证token
     */
//    public function serve():Response
//    {
//        $app=Factory::officialAccount(self::options());
//        $server=$app->server;
//        $response=$server->serve();
//        $response->send();
//        exit;
//    }

    public function sendMsg()
    {
        $this_month=date('Y-m-01',strtotime(date('Y-m-d')));
        $this_one=strtotime($this_month);
        $this_five=strtotime($this_month)+86400*5;
        $user_list=UserModel::where('status',1)->where('is_landlord',1)->column('openid','id');
        $list=ElectricDegrees::where('createtime','between',[$this_one,$this_five])->column('user_id');

        for ($i=0;$i<count($list);$i++){
            if (array_key_exists($list[$i],$user_list)){
                unset($user_list[$list[$i]]);
            }
        }

        $app=Factory::officialAccount(self::options());
        foreach ($user_list as $k=>$v){
            $app->template_message->send([
                'touser'=>$v,
                'template_id'=>'xWL48LSzCY3EyxvDw8qgg6IDMHxpxOnpEgc89aCt4G8',
                'data'=>[
                    'first'=>'抄送电表通知',
                    'keyword1'=>'请拍照上传电表信息',
                    'keyword2'=>date('Y-m-d',time())
                ]
            ]);
        }

    }

    public function auth(){
        $phone=$this->request->request('phone');
        $appid=trim(config('site.wechat_appid'));
        //$back_url=$this->request->domain().'/index.html#/';
        $back_url=$this->request->domain().'/h5/#/?phone='.$phone;
        $back_url=urlencode($back_url);
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$back_url.'&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
        $data=[
            'url'=>$url
        ];
        $this->success('成功',$data);
    }

    public function login()
    {
        $appid=trim(config('site.wechat_appid'));
        $appsercret=trim(config('site.wechat_appsecret'));
        $is_landlord=$this->request->request('is_landlord',0);
        $code=input('code');
        $avatar=input('avatar');
        $nickname=input('nickname');
        $sex=input('sex');
        if(empty($code)){
            $this->error('code必传');
        }
        $phone = $this->request->post('phone', '');//手机号注册后绑定微信用
        $url='https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsercret.'&js_code='.$code.'&grant_type=authorization_code';
        //$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $client=new Client();
        $res=$client->get($url)->getBody()->getContents();
        $data=json_decode($res,true);
        if (!empty($data['openid'])){
            /*$curl='https://api.weixin.qq.com/sns/userinfo?access_token='.$data['access_token'].'&openid=OPENID&lang=zh_CN';
            $info=$client->get($curl)->getBody()->getContents();
            $wechatInfo=json_decode($info,true);*/
            $is_has=UserModel::where('openid',$data['openid'])->find();
            if (!$is_has){
                $addData['nickname']=$nickname;
                $addData['openid']=$data['openid'];
                $addData['avatar']=$avatar;
                $addData['gender']=$sex==1 ? 0 : 1;
                $addData['status']=1;
                $addData['createtime']=time();
                $addData['warn_district']='';
                $addData['is_landlord']=$is_landlord;
                $udata = false;
                if($phone){
                    $udata = User::where(['mobile'=>$phone])->find();
                }
                if($udata){
                    $id['id'] = $udata['id'];
                    $usave['nickname']=$nickname;
                    $usave['openid']=$data['openid'];
                    $usave['avatar']=$avatar;
                    $usave['gender']=$sex==1 ? 0 : 1;
                    User::where(['mobile'=>$phone])->update($usave);
                }else{
                    $id=(new UserModel())->create($addData);
                    //注册奖励
                    if(config("site.register_give") > 0){
                        User::score(config("site.register_give"),$id['id'],"注册奖励");
                    }
                }
                $userInfo=UserModel::where('id',$id['id'])->find();
            }else{
                $userInfo=$is_has;
            }

            \app\common\library\Token::clear($userInfo['id']);
            $this->auth->direct($userInfo['id']);
            $userInfo['token']=$this->auth->getToken();
            if(!$userInfo['mobile']){
                $this->success('成功',$userInfo,101);
            }
            $this->success('成功',$userInfo);
        }else{
            $this->error('登录失败');
        }
    }
    /**
     * public function login()
    {
    $appid=trim(config('site.wechat_appid'));
    $appsercret=trim(config('site.wechat_appsecret'));
    $is_landlord=$this->request->request('is_landlord',0);
    $code=input('code');
    $avatar=input('avatar');
    $nickname=input('nickname');
    $sex=input('sex');
    if(empty($code)){
    $this->error('code必传');
    }
    $phone = $this->request->post('phone', '');//手机号注册后绑定微信用
    $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsercret.'&code='.$code.'&grant_type=authorization_code';
    $client=new Client();
    $res=$client->get($url)->getBody()->getContents();
    $data=json_decode($res,true);
    if (!empty($data['openid'])){
    $curl='https://api.weixin.qq.com/sns/userinfo?access_token='.$data['access_token'].'&openid=OPENID&lang=zh_CN';
    $info=$client->get($curl)->getBody()->getContents();
    $wechatInfo=json_decode($info,true);
    $is_has=UserModel::where('openid',$wechatInfo['openid'])->find();
    if (!$is_has){
    $addData['nickname']=$wechatInfo['nickname'];
    $addData['openid']=$wechatInfo['openid'];
    $addData['avatar']=$wechatInfo['headimgurl'];
    $addData['gender']=$wechatInfo['sex']==1 ? 0 : 1;
    $addData['status']=1;
    $addData['createtime']=time();
    $addData['warn_district']='';
    $addData['is_landlord']=$is_landlord;
    $udata = false;
    if($phone){
    $udata = User::where(['mobile'=>$phone])->find();
    }
    if($udata){
    $id['id'] = $udata['id'];
    $usave['nickname']=$wechatInfo['nickname'];
    $usave['openid']=$wechatInfo['openid'];
    $usave['avatar']=$wechatInfo['headimgurl'];
    $usave['gender']=$wechatInfo['sex']==1 ? 0 : 1;
    User::where(['mobile'=>$phone])->update($usave);
    }else{
    $id=(new UserModel())->create($addData);
    //注册奖励
    if(config("site.register_give") > 0){
    User::score(config("site.register_give"),$id['id'],"注册奖励");
    }
    }
    $userInfo=UserModel::where('id',$id['id'])->find();
    }else{
    $userInfo=$is_has;
    }
    if(!$userInfo['mobile']){
    $this->success('成功',$userInfo,101);
    }
    \app\common\library\Token::clear($userInfo['id']);
    $this->auth->direct($userInfo['id']);
    $userInfo['token']=$this->auth->getToken();
    $this->success('成功',$userInfo);
    }else{
    $this->error('登录失败');
    }
    }
     */
    /**
     * 绑定手机号
     */
    public function bindingphone()
    {
        $phone=$this->request->request('phone');
        $id=$this->request->request('id');
        $parent_id=$this->request->request('parent_id');
        $captcha=$this->request->request('captcha');
        if (!Sms::check($phone, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        if (!preg_match("/^1[3456789]\d{9}$/",$phone)) $this->error('手机号格式错误');
        $is_has=UserModel::where(['mobile'=>$phone,'status'=>1])->find();//查询绑定手机号信息
        $parent_data=UserModel::where(['id'=>$parent_id])->find();//推荐人
        $u_data=UserModel::where(['id'=>$id])->find();//被推荐人
        if($parent_data){
            $parent_user_id = $parent_data['id'];
        }else{
            $parent_user_id = 0;
        }
        $user_id = $id;
        if($is_has){//如果绑定的手机存在用户
           // $saveData['nickname']=$u_data['nickname'];
            $saveData['openid']=$u_data['openid'];
            $saveData['avatar']=$u_data['avatar'];
            $saveData['gender']=$u_data['gender'];
            $saveData['parent_user_id']=$parent_user_id;

            Db::name('user')->where('id',$is_has['id'])->update($saveData);
            $data['status'] = 0;
            $res = Db::name('user')->where('id',$id)->update($data);
            $user_id = $is_has['id'];
        }else{
            $data['mobile'] = $phone;
            $data['parent_user_id'] = $parent_user_id;
            $res = Db::name('user')->where('id',$id)->update($data);
            //$res=\app\admin\model\User::update(['mobile'=>$phone],['id'=>$this->auth->id]);
        }
        //邀请奖励
        if(config("site.parent_give") > 0 && $parent_user_id > 0){
            User::score(config("site.parent_give"),$parent_user_id,"邀请奖励");
        }
        $ret = $this->auth->direct($user_id);
        if ($res!==false && $ret) {
            $data = UserModel::where(['id'=>$user_id])->find();
            $this->success(__('Logged in successful'), $data);
           // $this->success('成功');
        }else {
            $this->error('失败');
        }
    }

    /**
     * 用户信息
     */

    public function info()
    {
        $uid=$this->request->request('uid');
        $userInfo=UserModel::where('id',$uid)->find();
        $this->auth->direct($uid);
        $userInfo['token']=$this->auth->getToken();
        if ($userInfo) $this->success('成功',$userInfo);
        else $this->error('未登录');
    }

    /**
     * 第三方 使用
     * 查询当前用余额
     */
    public function checkMoney()
    {
        $id=$this->request->request('phone');
        $key=$this->request->request('token');
        if (empty($id)||empty($key)) $this->error('缺少必传参数');
        $res=Manufacturer::where('token',$key)->find();
        if (!$res) $this->error('token已失效，请重新获取');
        $res1=UserModel::where('mobile',$id)->find();
        if(!$res1) $this->error('用户不存在');
        $res2=UserModel::where('id',$res1['id'])->value('money');
        $this->success('成功',$res2);
    }

    /*
     * 第三方 使用
     * 消费扣款
     */
    public function charge()
    {
        $id=$this->request->request('phone');
        $key=$this->request->request('token');
        $pay_money=$this->request->request('pay_money');
        $order_id=$this->request->request('order_id');
        $title=$this->request->request('title');
        if (empty($id)||empty($key) || ($pay_money==0) || empty($order_id)) $this->error('缺少必传参数');
        $res=Manufacturer::where('token',$key)->find();
        if (!$res) $this->error('token已失效，请重新获取');
        $res1=UserModel::where('mobile',$id)->find();
        if(!$res1) $this->error('用户不存在');
        $user_money=UserModel::where('id',$res1['id'])->value('money');
        if ($pay_money>$user_money) $this->error('余额不足');
        $balance=bcsub($user_money,$pay_money,2);
        $addData['orderid']=$order_id;
        $addData['title']=$title;
        $addData['amount']=$pay_money;
        $addData['createtime']=time();
        $addData['status']=1;
        $addData['user_id']=$res1['id'];
        $addData['paytime']=time();
        Db::startTrans();
        try{
            (new BillOrder())->insert($addData);
            UserModel::update(['money'=>$balance],['id'=>$res1['id']]);
            Db::commit();
            $this->success('成功');
        }catch (\think\Exception $e){
            $this->error('请求失败');
            Db::rollback();
        }
    }

    /**
     *  第三方 使用
     * 请求接口，错误日志入库
     */
    public function addErrLog()
    {

        $id=$this->request->request('phone');
        $key=$this->request->request('token');
        $secret_key=md5(config('site.secret_key'));
        $content=$this->request->request('info');
        if (empty($key)|| ($key!=$secret_key) || empty($content)) $this->error('缺少必传参数');
        $res1=UserModel::where('mobile',$id)->find();
        if(!$res1) $this->error('用户不存在');
        $addData['info']=$content;
        $addData['createtime']=time();
        $res2=ErrLog::create($addData);
        if ($res2) $this->success('成功');
        else $this->error('请求失败');
    }

    /**
     *  第三方 使用
     * 消费记录
     */
    public function billLog()
    {
        $id=$this->request->request('phone');
        $key=$this->request->request('token');
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $start_time=$this->request->request('start_time');
        $end_time=$this->request->request('end_time');
        if (empty($id)||empty($key)) $this->error('缺少必传参数');
        $res=Manufacturer::where('token',$key)->find();
        if (!$res) $this->error('token已失效，请重新获取');
        $res1=UserModel::where('mobile',$id)->find();
        if(!$res1) $this->error('用户不存在');
        $res2=BillOrder::where('user_id',$res1['id']);
        if (empty($start_time)){
            if (empty($end_time)) $res2=$res2;
            else $res2=$res2->where('createtime','<',strtotime($end_time)+60*60*24);
        }else{
            if (empty($end_time)) $res2=$res2->where('createtime','>',strtotime($start_time));
            else $res2=$res2->where('createtime','between',[strtotime($start_time),strtotime($end_time)+60*60*24]);
        }
        $res2=$res2->field('orderid,title,amount,paytime,status,createtime')->page($page,$limit)->select();
        $this->success('成功',$res2);
    }

    /**
     *  第三方 使用
     * 退款接口
     */
    public function backmoney()
    {
        $id=$this->request->request('phone');
        $key=$this->request->request('token');
        $refund_money=$this->request->request('money');
        $order_id=$this->request->request('order_id');
        if (empty($id)||empty($key) || empty($order_id) || empty($refund_money)) $this->error('缺少必传参数');
        $res=Manufacturer::where('token',$key)->find();
        if (!$res) $this->error('token已失效，请重新获取');
        $res1=UserModel::where('mobile',$id)->find();
        if(!$res1) $this->error('用户不存在');
        $user_money=UserModel::where('id',$res1['id'])->value('money');
        $balance=bcadd($user_money,$refund_money,2);
        $res2=BillOrder::where('orderid',$order_id)->find();
        if ($res2['status']==2){
            $this->error('请勿重复退款');
        }else{
            Db::startTrans();
            try{
                BillOrder::update(['status'=>2,'refund_money'=>$refund_money,'refund_time'=>time()],['orderid'=>$order_id,'user_id'=>$res1['id']]);
                UserModel::update(['money'=>$balance],['id'=>$res1['id']]);
                Db::commit();
                $this->success('成功');
            }catch (\think\Exception $e){
                $this->error('请求失败');
                Db::rollback();
            }
        }
    }

    /**
     *  第三方 使用
     *  对账单接口
     */
    public function tranlog()
    {
        $key=$this->request->request('secret_key');
        $secret_key=md5(config('site.secret_key'));
        if (empty($key)|| ($key!=$secret_key)) $this->error('请求失败');
        Config::set('upload.cdnurl', '');
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        $addData['attachfile']= cdnurl($attachment->url, true);

        $addData['createtime']=time();
        $addData['status']=1;
        $res2=CheckBill::create($addData);
        if ($res2) $this->success('成功');
        else $this->error('请求失败');

    }

    /**
     * 充值记录
     */
    public function rechargeLog()
    {
        $uid=$this->request->request('uid');
        $page=$this->request->request('page');
        $limit=$this->request->request('limit');
        $list=RechargeOrder::where('user_id',$uid)->where('status',1)->field('title,payamount,paytime')->page($page,$limit)->select();
        $count=RechargeOrder::where('user_id',$uid)->where('status',1)->count();
        $this->success('成功',compact('list','count'));
    }

    /**
     * 判断url地址并返回相应token
     */
    public function geturl()
    {
        $input=input();
//        if (!array_key_exists('url',$input)) $this->error('url不能为空');
//        $input['url']="http://stake.atx88.com/customer/pay/clientLogin?sn=SZ0262&type=chargePay";
        $mobile=$input['mobile'];
        $url=parse_url($input['url']);
//         echo '<pre>';
//         print_r($url);
//         echo '</pre>';
//         return;

        $manufacturer_id=ManufacturerUrl::where('url',$url['scheme'].'://'.$url['host'])->value('manufacturer_id');
        $manufacturer=Manufacturer::where('id',$manufacturer_id)->find();
        $go_url='';
        switch ($url['host']){
            case 'www.yjm2m.com':
                $device_id=substr($url['query'],strrpos($url['query'],"=")+1);
                $go_url=$manufacturer['url'].'?device_id='.$device_id .'&unique_id='.$mobile.'&secret_key='.$manufacturer['token'];
                break;
            case 'qqcharging.com':
                $device_id=substr($url['path'],strrpos($url['path'],"/")+1);
                $go_url=$manufacturer['url'].'?device_id='.$device_id .'&unique_id='.$mobile.'&secret_key='.$manufacturer['token'];
                break;
            case 'saas.smart.guodongiot.com':
                $list=explode('&',$url['query']);
                $device_id=substr($list[0],stripos($list[0],"=")+1);
                $go_url=$manufacturer['url'].'?device_id='.$device_id .'&unique_id='.$mobile.'&secret_key='.$manufacturer['token'];
                break;
            case 'stake.atx88.com':
                $query=substr($url['query'],0,strpos($url['query'], '&'));
                $device_id=substr($query,strrpos($query,"=")+1);
                $go_url=$manufacturer['url'].'?sn='.$device_id .'&type=chargePay' .'&unique_id='.$mobile.'&secret_key='.$manufacturer['token'].'&key=Khalg3OubbVzMkjYbrvuZw==';
                break;
            default:
                $go_url='';
                break;
        }
//        file_put_contents('ss11',print_r($go_url,true));
//         echo '<pre>';
//         print_r($go_url);
//         echo '</pre>';
//         return;
        $this->success('成功',$go_url);
    }

    /**
     * 余额充值
     */
    public function recharge()
    {
        $uid=$this->request->request('uid');
        $opeind=UserModel::where('id',$uid)->value('openid');
        $money=$this->request->request('number');
        $discount_id=$this->request->request('discount_id',0);
        if (!$money || $money < 0) {
            $this->error("充值金额必须大于0");
        }
        $type='wechat';
        $method='miniapp';
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        $title = '余额充值';
        //回调链接
        $notifyurl = $this->request->domain() . '/api/Wechat/notifyx/paytype/' . $type;
        $returnurl = $this->request->domain() . '/api/Wechat/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        $addData=[
            'orderid'=>$out_trade_no,
            'user_id'=>$uid,
            'title'=>$title,
            'amount'=>$money,
            'payamount'=>$money,
            'discount_id'=>$discount_id,
            'createtime'=>time()
        ];
        $res=(new RechargeOrder())->insert($addData);
        if ($res){
            $res1=Service::submitOrder($money, $out_trade_no, $type, $title, $notifyurl, $returnurl,$method,$opeind);
            $this->success('成功',$res1);

        }else{
            $this->error('创建订单失败');
        }
    }
    /**
     * 企业付款到零钱
     * 支付成功，回调
     */
    public function qinotifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            //你可以在此编写订单逻辑
            DepositOrder::update(['status'=>1],['orderid'=>$out_trade_no]);

        } catch (Exception $e) {
        }
        echo $pay->success();
    }
    /**
     * 余额充值回调
     * 支付成功，回调
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            //你可以在此编写订单逻辑
            RechargeOrder::update(['status'=>1,'paytime'=>time(),'paytype'=>'wap'],['orderid'=>$out_trade_no]);
            $order=RechargeOrder::where('orderid',$out_trade_no)->find();
            $info=UserModel::where('id',$order['user_id'])->find();
            $money=bcadd($order['amount'],$info['money'],2);
            UserModel::update(['money'=>$money],['id'=>$info['id']]);
            if($order['discount_id'] > 0){
                $dis_data = Discount::where('id',$order['discount_id'])->find();
                if($dis_data['duration'] > 0){
                    User::score($dis_data['duration'],$order['user_id'],'充值奖励');
                }

            }
        } catch (Exception $e) {
        }
        echo $pay->success();
    }

    /**
     * 支付返回，回调
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }


}